package com.h2cloud.service.jedis;

/**
 * @Package: com.h2cloud.jedis
 * @ClassName: JedisLockExample
 * @Author: wulongkai
 * @CreateTime: 2023/8/4 15:01
 * @Description:
 */

import redis.clients.jedis.Jedis;

import java.util.Arrays;
import java.util.Collections;

//@Slf4j
//@Component
//@Data
public class RedisClient {

    Jedis jedis = new Jedis("127.0.0.1", 6379);
    Long RELEASE_SUCCESS = 1L;

    private static final String LOCK_SCRIPT =
                    "local lock_key = 'lock:' .. KEYS[1] " +
                    "if redis.call('exists', lock_key) == 0 then " +
                    "    redis.call('hset', lock_key, ARGV[1], 1) " +
                    "    redis.call('expire', lock_key, ARGV[2]) " +
                    "    return 1 " +
                    "elseif redis.call('hexists', lock_key, ARGV[1]) == 1 then " +
                    "    redis.call('hincrby', lock_key, ARGV[1], 1) " +
                    "    redis.call('expire', lock_key, ARGV[2]) " +
                    "    return 1 " +
                    "else " +
                    "    return 0 " +
                    "end";

    private static final String UN_LOCK_SCRIPT =
            "local lock_key = 'lock:' .. KEYS[1] " +
            "if redis.call('hexists', lock_key, ARGV[1]) == 1 then " +
            "    local count = redis.call('hincrby', lock_key, ARGV[1], -1) " +
            "    if count <= 0 then " +
            "        redis.call('del', lock_key) " +
            "    end " +
            "end";

    public boolean lock(String lockKey, String requestId, int expireTime) {
        Object eval = jedis.eval(
                LOCK_SCRIPT,
                Collections.singletonList(lockKey),
                Arrays.asList(requestId, String.valueOf(expireTime))
        );
        return RELEASE_SUCCESS.equals(eval);
    }

    public void unLock(String lockKey, String requestId) {
        jedis.eval(UN_LOCK_SCRIPT, Collections.singletonList(lockKey), Collections.singletonList(requestId));
    }
}

